/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import beans.ResumenVotosBean;
import databeans.OpcionesEncuestaDataBean;
import java.io.IOException;
import java.io.OutputStream;
import java.text.AttributedString;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

/**
 *
 * @author Emerson
 */
public class MostrarGrafico  extends HttpServlet{
    protected void process(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        //DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        DefaultPieDataset piedataset = new DefaultPieDataset();
        try {
            OpcionesEncuestaDataBean oedb = new OpcionesEncuestaDataBean();
        
        List opciones = oedb.getVotosEncuesta(request.getParameter("idEncuesta"));
        Iterator it= opciones.iterator();
        double votos=0;
        while(it.hasNext()){
        ResumenVotosBean opcion= (ResumenVotosBean) it.next();
            votos += opcion.getVotos();
        }
        it=opciones.iterator();

        while(it.hasNext())
        {
        ResumenVotosBean opcion= (ResumenVotosBean) it.next();
       // dataset.addValue(opcion.getVotos(), opcion.getOpcion(), "Opciones");
        double porc = (opcion.getVotos()/votos)*100;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        String porce= nf.format(porc);
        piedataset.setValue(porce+ "% --> " + opcion.getOpcion(), opcion.getVotos());
        }


        } catch (Exception ex) {
            Logger.getLogger(MostrarGrafico.class.getName()).log(Level.SEVERE, null, ex);
        }
        //if(dataset.getRowCount()>0){
        /*JFreeChart chart = ChartFactory.createBarChart3D(
            "Resultados de Encuesta",       // titulo grafico
            "Preguntas",               // etiqueta de dominio
            "Votos",                  // etiqueta de rango
            dataset,                  // datos
            PlotOrientation.VERTICAL, // orientacion
            true,                     // incluir  leyenda
            true,                     // tooltips?
            false                     // URLs?
        );*/

        JFreeChart chart2= ChartFactory.createPieChart(
                "Resultados de Encuesta",
                piedataset,
                true,
                true,
                true);
        PiePlot plot = (PiePlot) chart2.getPlot();
        plot.setLegendLabelGenerator(new CustomLegendGenerator());
        //plot.setLabelGenerator(new generadorLabel());
        
        response.setContentType("image/jpeg");
        OutputStream out = response.getOutputStream();
        ChartUtilities.writeChartAsJPEG(out, chart2, 600, 400);
        out.close();
        //}
      
    }
/*static class generadorLabel implements PieSectionLabelGenerator{
public String generateSectionLabel(final PieDataset dataset,
final Comparable key) {
/* Creating a temporary string to hold value defined by us */
/*String temp = null;
if (dataset != null) {
/* Assigning the Value from dataset as a legend item for display */
/*temp = key.toString();
/* Modifying a particular legend item based on the Key name */

/*temp = temp.substring(0,temp.indexOf("%")+1);

}
/* Returning the formatted string back to set the label */
/*return temp;
}

        public AttributedString generateAttributedSectionLabel(PieDataset dataset, Comparable key) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }*/

    static class CustomLegendGenerator
implements PieSectionLabelGenerator {
/**
* Set customized legend in the pie chart
*
* @param dataset PieChart DataSet
* @param key Comparable Key
* @return Result String to be displayed
*/
public String generateSectionLabel(final PieDataset dataset,
final Comparable key) {
/* Creating a temporary string to hold value defined by us */
String temp = null;
if (dataset != null) {
/* Assigning the Value from dataset as a legend item for display */
temp = key.toString();
/* Modifying a particular legend item based on the Key name */

temp = temp.substring(temp.indexOf("%")+1);

}
/* Returning the formatted string back to set the label */
return temp;
}

        public AttributedString generateAttributedSectionLabel(PieDataset dataset, Comparable key) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        process(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        process(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>


}
